package com.ruoyi.project.meal.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FileUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.MyHandler;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.meal.domain.MealMilk;
import com.ruoyi.project.meal.domain.MealWorker;
import com.ruoyi.project.meal.service.IMealWorkerService;
import com.ruoyi.project.meal.vo.MealWorkerVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 职工报餐Controller
 * 
 * @author Sky
 * @date 2024-03-13
 */
@Controller
@RequestMapping("/meal/worker")
public class MealWorkerController extends BaseController
{
    private String prefix = "meal/worker";

    @Autowired
    private IMealWorkerService mealWorkerService;


    @GetMapping()
    public String worker()
    {
        return prefix + "/worker";
    }

    /**
     * 查询职工报餐列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MealWorker mealWorker)
    {
        startPage();
        List<MealWorker> list = mealWorkerService.selectMealWorkerList(mealWorker);
        return getDataTable(list);
    }

    @GetMapping("/reportShow")
    public String reportShow()
    {
        return prefix + "/workerReport";
    }

    /**
     * 报表
     */
    @PostMapping("/reportList")
    @ResponseBody
    public TableDataInfo reportList(MealWorker mealWorker)
    {
        startPage();
        List<MealWorkerVo> list = mealWorkerService.selectWorkerReport( mealWorker);
        return getDataTable(list);
    }


    /**
     * 导出职工报餐列表
     */
    @Log(title = "职工报餐", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MealWorker mealWorker , HttpServletResponse response)
    {
        String reportDate=String.valueOf(mealWorker.getParams().get("startTime"))+String.valueOf(mealWorker.getParams().get("endTime"));
        List<MealWorker> list = mealWorkerService.selectMealWorkerList(mealWorker);

        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "worker.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new MyHandler()).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("reportDate", reportDate);
            map.put("campus", mealWorker.getCampus());
            excelWriter.fill(map, writeSheet);
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 导出职工报餐列表
     */
    @Log(title = "职工报餐", businessType = BusinessType.EXPORT)
    @PostMapping("/exportReport")
    @ResponseBody
    public AjaxResult exportReport(MealWorker mealWorker , HttpServletResponse response)
    {
        String reportDate="";
        String startTime=String.valueOf(mealWorker.getParams().get("beginReportDate"));
        String endTime=String.valueOf(mealWorker.getParams().get("endReportDate"));
        if(!StringUtils.isEmpty(startTime)){
            reportDate=startTime+"-"+endTime;
        }
        List<MealWorkerVo> list = mealWorkerService.selectWorkerReport(mealWorker);
        int lunchTotal=0;
        int breakfastTotal=0;
        int dinnerTotal=0;
        if(list!=null && list.size()>0){
            for (MealWorkerVo mw:list ) {
                lunchTotal=lunchTotal+mw.getLunch();
                breakfastTotal=breakfastTotal+mw.getBreakfast();
                dinnerTotal=dinnerTotal+mw.getDinner();
            }
        }
        ExcelUtil<MealWorker> util = new ExcelUtil<MealWorker>(MealWorker.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "worker.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new MyHandler()).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("lunchTotal", lunchTotal);
            map.put("breakfastTotal", breakfastTotal);
            map.put("dinnerTotal", dinnerTotal);
            map.put("reportDate", reportDate);
            map.put("campus", mealWorker.getCampus());
            excelWriter.fill(map, writeSheet);
        }
        return AjaxResult.success(fileName);
    }



    /**
     * 新增职工报餐
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存职工报餐
     */
    @Log(title = "职工报餐", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MealWorker mealWorker)
    {
        return toAjax(mealWorkerService.insertMealWorker(mealWorker));
    }

    /**
     * 修改职工报餐
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        MealWorker mealWorker = mealWorkerService.selectMealWorkerById(id);
        mmap.put("mealWorker", mealWorker);
        return prefix + "/edit";
    }

    /**
     * 修改保存职工报餐
     */
    @Log(title = "职工报餐", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MealWorker mealWorker)
    {
        return toAjax(mealWorkerService.updateMealWorker(mealWorker));
    }

    /**
     * 删除职工报餐
     */
    @Log(title = "职工报餐", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(mealWorkerService.deleteMealWorkerByIds(ids));
    }

    /**
     * 查询报餐明细
     */
    @GetMapping("/detail/{data}")
    public String detail(@PathVariable("data") String data, ModelMap mmap)
    {
        mmap.put("data",data);
        return "meal/worker/workerReportList";
    }
}
